/**
 *获取菜单树形结构
 */
'use strict';

const conn = require('../../libs/DB/Conn');
const _ = require('underscore');

function fincChildren(parentNode, menuList) {
    let childrens = _.filter(menuList, function (menu) {
        return menu.parent_id === parentNode.menu_id;
    });//没有遍历到子菜单即执行结束
    if (childrens.length) {
        //递归寻找子菜单，直到没有发现子菜单结束递归
        parentNode['children'] = childrens;
        _.forEach(childrens, function (childrenNode) {
            fincChildren(childrenNode, menuList);
        });
    }
}
function getTreeData(menuList) {
    //先获取一级菜单
    let parentNodeList = _.filter(menuList, function (v) {
        return v.parent_id === 0;
    });
    _.forEach(parentNodeList, function (parentNode) {
        //对所有一级菜单进行循环，并调用寻找子节点函数
        fincChildren(parentNode, menuList);
    });
    return parentNodeList;
}

module.exports = async function (params) {
    let sysMenuType = params.sysMenuType;

    let sql = `SELECT * FROM sys_menu WHERE menu_type = ?`;
    let rec = await conn(sql, [sysMenuType]);
    getTreeData(rec);//将菜单数据转换为树形结构

    return { success: true, data: getTreeData(rec) };
};
